<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    okText="保存并安排任务"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">

        <!--<a-form-model-item :labelCol="labelCol"  :wrapperCol="wrapperCol" label="任务类名" prop="jobClassName" hasFeedback >-->
          <!--<a-input placeholder="请输入任务类名" v-model="model.jobClassName" />-->
        <!--</a-form-model-item>-->
        <a-form-model-item label="任务类名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskId">
          <a-select
            v-model="model.taskId"
            filterable
            allowClear
            default-first-option
            show-search
            optionFilterProp="label"
            @change="onTaskChange"
            placeholder="请选择任务类">
            <a-select-option
              v-for="item in data2"
              :key="item.id"
              :value="Number(item.id)"
              :label="item.taskName">
              {{ item.taskName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="Cron表达式" prop="cronExpression">
          <!-- <j-cron v-model="model.cronExpression"/>-->
          <j-easy-cron v-model="model.cronExpression" />
        </a-form-model-item>
        <!--<a-form-model-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="参数" prop="parameter" >-->
          <!--<a-textarea placeholder="请输入参数" :rows="5" v-model="model.parameter" />-->
        <!--</a-form-model-item>-->
        <!--<a-form-model-item :labelCol="labelCol"  :wrapperCol="wrapperCol" label="描述" prop="description">-->
          <!--<a-textarea placeholder="请输入描述" :rows="3" v-model="model.description" />-->
        <!--</a-form-model-item>-->

        <el-divider v-if="this.taskType==1" content-position="left">爬虫信息</el-divider>

        <a-form-model-item v-if="this.taskType==1" label="网站" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="websiteId">
          <a-select
            v-model="model.websiteId"
            filterable
            allowClear
            default-first-option
            show-search
            optionFilterProp="label"
            @change="change"
            placeholder="请选择网站">
            <a-select-option
              v-for="item in data3"
              :key="item.id"
              :value="Number(item.id)"
              :label="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item v-if="this.taskType==1" label="文章" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="docIds">
          <a-select
            v-model="model.docIds"
            mode="multiple"
            filterable
            allowClear
            default-first-option
            show-search
            optionFilterProp="label"
            placeholder="请选择文章">
            <a-select-option
              v-for="item in data4"
              :key="item.id"
              :value="Number(item.id)"
              :label="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item v-if="this.taskType==1" label="知识库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="knowledgeBase">
          <a-select  v-model="model.knowledgeBase"
                     filterable
                     allowClear
                     default-first-option
                     placeholder="请选择知识库"
          >
            <a-select-option
              v-for="item in data5"
              :key="item.id"
              :value="item.roleName">
              {{ item.roleName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol"  label="状态" prop="status">
          <j-dict-select-tag type="radioButton" v-model="model.status" dictCode="quartz_status"/>
        </a-form-model-item>

      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction,getAction } from '@/api/manage'
  // import JCron from "@/components/jeecg/JCron";
  import {duplicateCheck } from '@/api/api'
  import cronValidator from "@/components/jeecg/JEasyCron/validator";

  export default {
    name: "QuartzJobModal",
    components: {
      // JCron,
    },
    data () {
      return {
        title:"操作",
        buttonStyle: 'solid',
        CrawlId: '',
        visible: false,
        model: {
          docIds: [],
        },
        data2: [],
        data3: [],
        data4: [],
        data5: [],
        taskType: null,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        cron: {
          label: '',
          value: ''
        },
        confirmLoading: false,
        validatorRules: {
          cronExpression: [
            {required: true, message: '请输入cron表达式!'},
            {validator: cronValidator,}
          ],
          taskId: [
            {validator: this.validateWorkNo},
            {required: true, message: '任务类名不能为空!'}
            ],
          websiteId:[
            {required: true, message: '请选择网站!'}
          ],
          knowledgeBase:[
            {required: true, message: '请选择知识库!'}
          ]
        },
        url: {
          list2: "/sys/IndexTask/list",
          list3: "/sys/CrawlWebsite/list",
          list4: "/sys/CrawlSiteFeatureDocCont/list",
          list5:  '/sys/knowledgebase/list',
          add: "/sys/quartzJob/add",
          edit: "/sys/quartzJob/edit",
        },
      }
    },
    created () {
      this.loadData2();
      this.loadData3();
      this.loadData4();
    },
    methods: {

      onTaskChange(value) {
        this.$set(this.model, 'websiteId',undefined);
        this.$set(this.model, 'docIds',[]);
        this.$set(this.model, 'knowledgeBase',undefined);
        this.data4=[];
        console.log('=====Selected value===========:'+ value);
        const selectedTask = this.data2.find(item => item.id == value);
        console.log("========selectedTask=======" + JSON.stringify(selectedTask))
        if (selectedTask) {
          console.log('Selected task:', selectedTask);
          this.taskType = selectedTask.taskType;
        } else {
          console.warn('No matching task found for the given value.');
        }
      },

      change(value) {
        this.$set(this.model, 'docIds',[]);
        this.CrawlId = value
        this.getFeatureDocList();
      },

      getFeatureDocList(){
        console.log("========this.CrawlId=======" + JSON.stringify(this.CrawlId))
        if (this.CrawlId!=undefined&&this.CrawlId!=null){
          let params = {}
          params.websiteId = this.CrawlId
          getAction(this.url.list4, params).then((res) => {
            if (res.success) {
              this.data4 = res.result.records
            }
          })
        } else {
          this.data4=[];
        }
        console.log("========this.data4=======" + JSON.stringify(this.data4))
      },

      loadData2() {
        let params = {}
        getAction(this.url.list2, params).then((res) => {
          if (res.success) {
            this.data2 = res.result.records
          }
        })
      },

      loadData3() {
        let params = {}
        getAction(this.url.list3, params).then((res) => {
          console.log("========res========" + JSON.stringify(res))
          if (res.success) {
            this.data3 = res.result.records
          }
        })
      },
      loadData4() {
        let params = {}
        getAction(this.url.list5, params).then((res) => {
          if (res.success) {
            this.data5 = res.result.records
          }
        })
      },

      add() {
        console.log("========新增========")
        // 统一设置默认值
        this.edit({
          cronExpression: '* * * * * ? *',
          status: 0,
          a:'add'
        })
      },
      edit (record) {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs.form.resetFields()
          this.model = Object.assign({}, record)
          console.log("========Object========" + JSON.stringify(this.model))
          this.taskType=this.model.taskType
          if (this.model.a!="add"&&this.model.taskType==1){
            var modelJson = JSON.parse(this.model.parameter);
            console.log("========modelJson========" + JSON.stringify(modelJson))
            this.CrawlId = modelJson.crawl_params.website_id;
            if (this.CrawlId!=undefined && this.CrawlId!=null) {
              this.getFeatureDocList();
              this.$set(this.model, 'websiteId', modelJson.crawl_params.website_id);
              this.$set(this.model, 'docIds', modelJson.crawl_params.doc_ids);
              this.$set(this.model, 'knowledgeBase', modelJson.job_params.kb);
            }else {
              this.$set(this.model, 'websiteId',undefined);
              this.$set(this.model, 'docIds',[]);
              this.$set(this.model, 'knowledgeBase',undefined);
            }
          }
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate((ok, err) => {
          if (ok) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }

            console.log('--------提交参数------',this.model)
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
                that.close();
              }
            }).finally(() => {
              that.confirmLoading = false;
            })

          }
        })
      },
      handleCancel () {
        this.taskType=null;
        this.close()
      },

      validateWorkNo(rule, value, callback){
        let params = {
          tableName: 'sys_quartz_job',
          fieldName: 'task_id',
          fieldVal: value,
          dataId: this.model.id,
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("任务类名已存在!")
          }
        })
      },

    }
  }
</script>

<style scoped>

</style>